package autoNumber

import (
	"jiabo/appframework/libs/common"
	"jiabo/appframework/libs/db"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
)

type AutoNumber struct {
	Id     bson.ObjectId `bson:"_id,omitempty" json:"-"`
	Key    string        `bson:"key" json:"key"`
	Number int           `bson:"number" json:"number"`
}

//根据不同需要编写不同格式自动编码的处理方法
func GetFormattedNumber(key string) (result string, err error) {
	err = nil
	res, err1 := GetNewNumber(key)
	if err1 != nil {
		result = ""
		err = err1
		//fmt.Println(err)
		return
	}
	switch key {
	case "department":
		result = "D" + FormatNumberSize(res, 4)
	case "orgnization":
		result = "Org" + FormatNumberSize(res, 5)

		//继续case其它的就行了
	}

	return
}

//获得一个固定长度的数字字符串例如4位长度的1，为0001
func FormatNumberSize(i int, size int) (result string) {
	s := common.IntToString(i)
	//fmt.Println(s)
	ln := len(s)
	//fmt.Println(ln)
	if ln >= size {
		result = s
		return
	} else {
		for j := 0; j < size-ln; j++ {
			s = "0" + s
		}
		result = s
		return
	}
}

//每次获取新号码，都会将自动编号加1
func GetNewNumber(key string) (result int, err error) {
	err = nil
	searchResults := AutoNumber{}

	query := func(c *mgo.Collection) error {
		fn := c.Find(bson.M{"key": key}).One(&searchResults)
		return fn
	}
	search := func() error {
		return db.WithCollection("autonumbers", query)
	}
	err = search()

	if searchResults.Id != "" {
		result = searchResults.Number + 1
		autonumber := searchResults
		autonumber.Number = autonumber.Number + 1
		update := func(c *mgo.Collection) error {
			fn := c.Update(bson.M{"key": key}, autonumber)
			return fn
		}

		updateExec := func() error {
			return db.WithCollection("autonumbers", update)
		}

		err = updateExec()
	} else {
		result = 1
		var autonumber2 AutoNumber
		autonumber2.Key = key
		autonumber2.Number = 1

		insert := func(c *mgo.Collection) error {
			fn := c.Insert(autonumber2)
			return fn
		}

		insertExec := func() error {
			return db.WithCollection("autonumbers", insert)
		}

		err = insertExec()
	}

	return
}
